package marcis.stopwatch;


import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;



public class SimpleWatch {

    private static final Logger log = Logger.getLogger(SimpleWatch.class);

    private final List<Long> times = new ArrayList<Long>();

    private String action;

    private boolean start;

    public void press(String action) {
        this.action = action;
        addTime(System.currentTimeMillis());
        start = !start;
        if (start) {
            log.info("STARTED " + action);
        } else {
            log.info("FINISHED " + action + ", total time: " + getTotalTime() + " seconds.");
        }
    }


    private String getTotalTime() {
        Long end = getEndTime();
        Long start = getStartTime();
        if (start == null || end == null) {
            return "N/A";
        }
        double delta = (end - start) / 1000.0;
        return Double.toString(delta);
    }

    private void addTime(Long time) {
        if (times.size() > 2) {
            times.clear();
        }
        times.add(time);
    }

    public Long getStartTime() {
        try {
            return times.get(0);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

    public Long getEndTime() {
        try {
            return times.get(1);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

}
